package com.bw.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.biz.mapper.TbOrderMapper;
import com.bw.biz.mapper.TbProductMapper;
import com.bw.biz.pojo.TbBill;
import com.bw.biz.mapper.TbBillMapper;
import com.bw.biz.pojo.TbOrder;
import com.bw.biz.pojo.TbProduct;
import com.bw.biz.service.TbBillService;
import com.bw.core.creditStatus.BillStatus;
import com.bw.core.creditStatus.DeleteStatus;
import com.bw.core.result.ResponseResult;
import com.bw.core.utils.TimeUtil;
import com.bw.core.vo.NoteMsgVo;
import com.bw.core.vo.RepayVo;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 账单表&还款计划表 服务实现类
 * </p>
 *
 * @author lv
 * @since 2021-03-23
 */
@Service
public class TbBillServiceImpl extends ServiceImpl<TbBillMapper, TbBill> implements TbBillService {
    @Autowired
    private TbBillMapper billMapper;
    @Autowired
    protected TbProductMapper productMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    //定时查询是否该还款
    public void repayPlan(){
        System.out.println("定时查询是否该还款");

        //查询处于待还款的数据
        QueryWrapper<TbBill> wrapper = new QueryWrapper<>();
        wrapper.eq("bill_status", BillStatus.BILL_NONE_REFUND);//查询状态为待还款的
        List<TbBill> tbBills = billMapper.selectList(wrapper);
        if(CollectionUtil.isEmpty(tbBills)){
            return;
        }
        for (TbBill bill : tbBills) {
            //循环遍历所有待还款的账单，然后去查找对应的商品  ---用于值计算---
            HashMap<String, Object> map = new HashMap<>();
            map.put("product_name",bill.getProductName());
            TbProduct product = productMapper.selectByMap(map).get(0);
            if (ObjectUtil.isNull(product)){
                return;
            }

            Date date = new Date();
            TimeUtil timeUtil = new TimeUtil();
            //获取当期还款的最后七天
            Date warnTime = timeUtil.lastTimeUtil(bill.getEndDate());
            if (date.equals(warnTime)){
                //如果账单表中有结束时间和当前时间一样的，就通知用户还款
                NoteMsgVo noteMsgVo = new NoteMsgVo();
                //获取用户手机号
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("order_no",bill.getOrderNo());
                TbOrder order = orderMapper.selectByMap(map1).get(0);

                noteMsgVo.setNoteMsg("您当期还款剩余时间为7天，请尽快还款");
                noteMsgVo.setPhone(order.getUserPhone());
                noteMsgVo.setSmsType(1);
                String toJSONString = JSON.toJSONString(noteMsgVo);
                amqpTemplate.convertAndSend("item_note",toJSONString);
            }
            Date endTime = timeUtil.nextMonthTimeUtil(bill.getEndDate());
            //执行当前时间超过还款期限
            if (date.after(bill.getEndDate()) && date.before(endTime)){
                QueryWrapper<TbBill> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("bill_no", bill.getBillNo());
                //逾期天数
                Date dateTime = new Date();
                Date createDate = bill.getCreateDate();//创建时间
                int l = (int) DateUtil.betweenDay(createDate, dateTime, true);
                int day = l+1;

                bill.setOverdue(day);
                BigDecimal fa = product.getProductDefaultInterest(); //罚息
                BigDecimal ben = bill.getRefoundPrincipal();//本金
                BigDecimal overMoney = fa.multiply(ben);
                BigDecimal totalOverMoney = overMoney.multiply(BigDecimal.valueOf(day));

                //修改逾期天数
                bill.setOverdue(day);
                //修改账单状态
                bill.setBillStatus(BillStatus.BILL_OVERDUE);
                //修改罚息金额
                bill.setRefoundDefaultInterestMoney(totalOverMoney);
                //修改总共应还金额
                BigDecimal money = bill.getRefoundMoney();
                bill.setRefoundTotalFee(money.add(totalOverMoney));
                //提交修改
                billMapper.update(bill,queryWrapper);

                //通知用户用户逾期天数，提醒该还款了
                NoteMsgVo noteMsg = new NoteMsgVo();
                //获取用户手机号
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("order_no",bill.getOrderNo());
                TbOrder order = orderMapper.selectByMap(map1).get(0);
                noteMsg.setNoteMsg("您已经逾期"+day+"天了，请尽快还款");
                noteMsg.setPhone(order.getUserPhone());
                noteMsg.setSmsType(4);
                String toJSONString = JSON.toJSONString(noteMsg);
                amqpTemplate.convertAndSend("item_note",toJSONString);


            }
            //如果上一期已还款，就更改下一期的状态
            if (bill.getStartDate().equals(date)){
                QueryWrapper<TbBill> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("bill_period",bill.getBillPeriod()-1);
                TbBill tbBill = billMapper.selectList(queryWrapper).get(0);
                if (tbBill.getBillPeriod().equals(BillStatus.BILL_REFUND_SUCCESS)){
                    bill.setBillStatus(BillStatus.BILL_NONE_REFUND);
                    billMapper.update(bill,wrapper);
                }
            }
        }
    }

    //还款成功
    @Override
    public void repayment(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        RepayVo repayVo = JSONObject.toJavaObject(jsonObject, RepayVo.class);
        QueryWrapper<TbBill> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",repayVo.getOrderNo());
        wrapper.eq("bill_status", BillStatus.BILL_NONE_REFUND);
        TbBill bill = billMapper.selectList(wrapper).get(0);

        Date date = new Date();
        //修改账单状态
        bill.setBillStatus(BillStatus.BILL_REFUND_SUCCESS);
        //如果是逾期还款就更改下一期状态
        if (date.after(bill.getEndDate())){
            QueryWrapper<TbBill> queryWrapper = new QueryWrapper<>();
            wrapper.eq("order_no",repayVo.getOrderNo());
            wrapper.eq("bill_period", bill.getBillPeriod()+1);
            TbBill tbBill = billMapper.selectList(queryWrapper).get(0);
            if (!ObjectUtil.isNull(tbBill)){
                tbBill.setBillStatus(BillStatus.BILL_NONE_REFUND);
                billMapper.update(tbBill,queryWrapper);
            }
        }
        //添加还款时间
        bill.setRefoundDate(new Date());
        //实际还款金额
        bill.setRefoundRealMoney(bill.getRefoundTotalFee());
        bill.setIsDelete(DeleteStatus.IS_DELETE);

        billMapper.update(bill,wrapper);
        //通知用户还款成功
        Date date1 = new Date();
        String s = date1.toLocaleString();
        NoteMsgVo noteMsg = new NoteMsgVo();
        //获取用户手机号
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("order_no",bill.getOrderNo());
        TbOrder order = orderMapper.selectByMap(map1).get(0);
        noteMsg.setNoteMsg("尊敬的用户，您于"+s+"还款成功");
        noteMsg.setPhone(order.getUserPhone());
        noteMsg.setSmsType(4);
        String toJSONString = JSON.toJSONString(noteMsg);
        amqpTemplate.convertAndSend("item_note",toJSONString);
    }

    @Override
    public ResponseResult affrimRepay() {
//        redisTemplate.opsForValue().get()
        QueryWrapper<TbProduct> wrapper = new QueryWrapper<>();
        wrapper.eq("product_name","超值商品1");
        List<TbProduct> tbProducts = productMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(tbProducts)){
            System.out.println("集合为空");
            return ResponseResult.error(500,"为空");
        }
        TbProduct tbProduct = tbProducts.get(0);
        if (ObjectUtil.isNull(tbProduct)){
            System.out.println("为空");
        }else{
            System.out.println(tbProduct);
            System.out.println("不为空");
        }
        return null;
    }

    public static void main(String[] args) {

    }
}
